package de.ars.client.items.elements;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;


import com.sun.lwuit.Font;
import com.sun.midp.io.j2me.storage.File;

import de.ars.client.Main;
import de.ars.common.IDataModelConstants;
import de.ars.common.ISharedResources;

public class StarItem extends AbstractItem
{
	private int value = 0;
	private Image upperLayer = null;
	private Image underLayer = null;
	private int height = 12;
	private int width; 
	
	private int widthText = 0;
	private boolean editable = false;
	private Font font;
	private StarItemListener listener = null;
	
	public StarItem(String _text,String _value,boolean _editable)
	{
		this.text = _text;
		this.value = Integer.parseInt(_value);
		this.editable = _editable;
		this.font = Main.getInstance().getFont( 0 );
		underLayer = ISharedResources.IMAGE_STARS_GRAY;
		
		widthText = font.stringWidth( this.text );
		width = widthText + ISharedResources.IMAGE_STARS.getWidth()+ 2 * IDataModelConstants.DEFAULT_MARGIN;
		height = Main.getInstance().getFont( 0 ).getHeight() + 2;
		updateStarImage();
	}
	
	public String getValue()
	{
		return new String(""+this.value+"");
	}
	
	public void paint( Graphics g, boolean selected)
	{
		if( selected )
        {
            g.drawRect( 0, 0, this.width + 1, this.height + 1 );
            g.setColor( 0xffffffff );
            g.fillRect( 1, 1, this.width, this.height);
            g.setColor( 0x00000000 );
        }
		g.drawString( text, IDataModelConstants.DEFAULT_MARGIN, (this.height+1)/2-this.font.getHeight()/2, Graphics.TOP | Graphics.LEFT );
		g.drawImage( underLayer,  IDataModelConstants.DEFAULT_MARGIN + widthText + 2,  (this.height+1)/2-this.underLayer.getHeight()/2, Graphics.TOP | Graphics.LEFT );
		if( value != 0 )
        {
            if (upperLayer != null)
            	g.drawImage( upperLayer,  IDataModelConstants.DEFAULT_MARGIN + widthText + 2,  IDataModelConstants.DEFAULT_MARGIN/2+1, Graphics.TOP | Graphics.LEFT );
        }
	}
	
	public void keyPressed(int arg0)
	{
		if (editable)
		{
			if (arg0 == -3)
				value--;
			if (arg0 == -4)
				value++;
			updateStarImage();
		}
	}
	
	private void updateStarImage()
	{
		if (value < 0)
			value = 0;
		if (value > 5)
			value = 5;
		
		if(value > 0) 
			upperLayer = Image.createImage( ISharedResources.IMAGE_STARS, 0, 0, value*12, ISharedResources.IMAGE_STARS.getHeight(), Sprite.TRANS_NONE );
		else
			upperLayer = null;
		if (this.listener != null)
			this.listener.valueChanged();
	}
	
	public int getHeight()
	{
		File.getStorageRoot();
		return this.height;
	}
	
	public void setValue(int _value)
	{
		this.value = _value;
		updateStarImage();
	}
	
	public void setListener(StarItemListener _listener)
	{
		this.listener = _listener;
	}
}
